import json

from fastapi import Request, APIRouter, Body
from typing import Optional
from core.Response import success
from models.models import Post, PostDteta, Tag
from schemas.posts import serialize_posts

router = APIRouter(prefix='')


@router.get('/yh')
async def guanhua(request: Request, page: Optional[int] = 1, page_size: Optional[int] = 10):
    offset = (page-1) * page_size
    print(page, page_size, 888888)
    recent_posts_queryset = await Post.filter(tags=2).order_by('id').limit(page_size).offset(offset)
    recent_posts = await serialize_posts(recent_posts_queryset)

    # 提取 recent_posts_queryset 中的 id 列表
    id_list = [post.id for post in recent_posts_queryset]

    # 根据 id 列表查询 PostDteta 表并获取 images 字段数据
    postdeta_queryset = await PostDteta.filter(id__in=id_list).order_by('id').limit(page_size)
    postdeta_images = {post.id: post.imageSrc[:4] for post in postdeta_queryset}

    # 将 postdeta_images 替换掉 posts 表中的 images 字段
    for post in recent_posts:
        # print(postdeta_images.get(post.id, []))
        post.imageSrc = postdeta_images.get(post.id, [])

    # 将 Pydantic 模型转换为字典
    recent_posts_dict = [post.dict() for post in recent_posts]

    return success(data={
        'posts': recent_posts_dict,
        'total': await Post.filter(tags=2).count()
    })


@router.get('/xunhui')
async def xunhui(request: Request, page: Optional[int] = 1, page_size: Optional[int] = 10):
    offset = (page - 1) * page_size
    print(page, page_size, 888888)

    # 获取所有满足 payType=3 的 PostDteta
    post_details_queryset = PostDteta.filter(payType=3).order_by('id')  # 不要加 await

    # 获取总记录数，确保这时候还是查询集
    total_count = await post_details_queryset.count()  # 这里可以正常计算

    # 对 PostDteta 查询结果进行分页
    post_details_page = await post_details_queryset.limit(page_size).offset(offset)

    if not post_details_page:
        return success(data={'posts': [], 'total': total_count})  # 如果没有找到相关的 post_detail 返回空列表

    # 提取 post_detail 的 ID 列表
    id_list = [post_detail.id for post_detail in post_details_page]

    # 根据 ID 列表查询 Post 表并获取相关数据
    recent_posts_queryset = await Post.filter(id__in=id_list).order_by('id').limit(page_size)
    recent_posts = await serialize_posts(recent_posts_queryset)

    # 提取 recent_posts_queryset 中的 id 列表
    recent_id_list = [post.id for post in recent_posts_queryset]

    # 根据 ID 列表查询 PostDteta 表并获取 images 字段数据
    postdeta_queryset = await PostDteta.filter(id__in=recent_id_list).order_by('id')
    postdeta_images = {post.id: post.imageSrc[:4] for post in postdeta_queryset}

    # 将 postdeta_images 替换掉 posts 表中的 images 字段
    for post in recent_posts:
        post.imageSrc = postdeta_images.get(post.id, [])

    # 将 Pydantic 模型转换为字典
    recent_posts_dict = [post.dict() for post in recent_posts]

    return success(data={
        'posts': recent_posts_dict,
        'total': total_count
    })

